package com.leyou.auth.service.Impl;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public String login(String username, String password) {
        
        //判断用户是否为空
        User user = userClient.queryUser(username, password);
        //初始化载荷
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        //生成jwt
        String jwt = null;
        try {
            jwt = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
        } catch (Exception e) {
            throw new LyException(ExceptionEnums.LOGIN_ERROR);
        }

        return jwt;
    }

    //使用公钥解析jwt，获取用户信息
    @Override
    public UserInfo verify(String token) {


        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            if (userInfo==null){
                throw new LyException(ExceptionEnums.LOGIN_ERROR);
            }
            return userInfo;
        } catch (Exception e) {
          throw new LyException(ExceptionEnums.LOGIN_ERROR);
        }

    }
}
